<script setup>
import { reactive, ref, onMounted } from "vue";
import { fbtypes, captcha, countys, feedback } from "@/api/index";
import { showFailToast, showSuccessToast, showDialog } from "vant";
import { useRouter } from 'vue-router';
const router = useRouter(); // 获取 router 实例
defineOptions({
  name: "Question"
});

// 响应式表单数据
const formData = ref({
  title: '',	//string	是	标题
  type_id: '',	//integer	是	问题类型ID
  contacts: '',	//	string	是	姓名
  mobile: '',	//	string	是	联系电话
  county: '',	//	integer	是	所属区县ID
  community: '',	//	string	是	小区名称
  content: '',	//	string	是	问题内容
  captcha: '',	//	string	是	验证码
  captchaid: '',	//	string	是	验证码id

});

// 类型选择
const type = ref('');
const showPicker_type = ref(false);
const columns_type = ref([]);
const fetchData_type = async () => {
  try {
    //API 请求
    const response = await fbtypes();
    console.log(response);

    columns_type.value = response.data.map(e => {
      return { text: e.name, value: e.id }
    });
  } catch (err) {
  } finally {
  }
};
// 在组件挂载时调用 fetchData
onMounted(fetchData_type);
const onConfirm_type = ({ selectedOptions }) => {
  type.value = selectedOptions[0]?.text;
  formData.value.type_id = selectedOptions[0]?.value;
  showPicker_type.value = false;
};

// 区域选择
const county = ref('');
const showPicker_county = ref(false);
const columns_county = ref([]);
// 获取区域列表 /api/index/countys
const fetchData_countys = async () => {
  try {
    //API 请求
    const response = await countys();
    console.log(response);

    columns_county.value = response.data.map(e => {
      return { text: e.name, value: e.id }
    });
  } catch (err) {
  } finally {
  }
};
// 在组件挂载时调用 fetchData
onMounted(fetchData_countys);
const onConfirm_county = ({ selectedOptions }) => {
  county.value = selectedOptions[0]?.text;
  formData.value.county = selectedOptions[0]?.value;
  showPicker_county.value = false;
};




// 获取验证码
const blobToBase64 = (blob) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(blob); // 将 Blob 转为 Base64
  });
};
const captchaImgData = ref('');
const fetchData_captcha = async () => {
  const randomPositiveNumber = Math.ceil(Math.random() * 100); // 生成 1-100 的随机正整数
  formData.value.captchaid = randomPositiveNumber
  try {
    //API 请求
    const response = await captcha({ id: randomPositiveNumber });
    console.log(response);
    // 将 Blob 转换为可用的 URL
    captchaImgData.value = URL.createObjectURL(response);
    // const base64Image = await blobToBase64(response);
    // console.log(base64Image); // Base64 格式
    // captchaImgData.value = base64Image
  } catch (err) {
  } finally {
  }
};
onMounted(fetchData_captcha);

const show = ref(false);
const code = ref('');
const msg = ref('您的问题已被受理, 请妥善保管此查询码, 于3-7日内凭此码查询反馈结果');
const onSubmit = async (values) => {
  console.log('submit', formData.value);
  try {
    //API 请求
    const response = await feedback(formData.value);
    console.log(response);
    if (response.code == 1) {
      msg.value = response.msg;
      code.value = response.data.code;
      show.value = true;
      // showSuccessToast(response.msg);
      formData.value.captcha = ''
      fetchData_captcha()

    } else {
      showFailToast(response.msg);
    }

  } catch (err) {
  } finally {
  }
};

const formRef = ref(null);

const resetForm = () => {
  type.value = ''
  county.value = ''
  // Reset form data to initial state
  formData.value = {
    title: '',	//string	是	标题
    type_id: '',	//integer	是	问题类型ID
    contacts: '',	//	string	是	姓名
    mobile: '',	//	string	是	联系电话
    county: '',	//	integer	是	所属区县ID
    community: '',	//	string	是	小区名称
    content: '',	//	string	是	问题内容
    captcha: '',	//	string	是	验证码
    captchaid: '',	//	string	是	验证码id

  };
  // Reset form validation
  formRef.value.resetValidation();
};

const copyText = async () => {

  resetForm()
  // try {
  //   show.value = false
  //   await navigator.clipboard.writeText(code.value);
  //   showSuccessToast('复制成功');
  //   console.log('文本已复制到剪贴板');
  // } catch (err) {
  //   showFailToast('复制失败');
  //   console.error('复制到剪贴板失败', err);

  // }
  const textarea = document.createElement('textarea');
  textarea.value = code.value;
  textarea.style.position = 'fixed'; // 防止滚动条移动
  document.body.appendChild(textarea);
  textarea.focus();
  textarea.select();
  try {
    const successful = document.execCommand('copy');
    console.log(successful ? '复制成功' : '复制失败');
    if (successful) {
      showSuccessToast('复制成功');
      show.value = false
    } else {
      showFailToast('复制失败');
    }
  } catch (err) {
    console.error('复制失败:', err);
    showFailToast('复制失败');
  }

  document.body.removeChild(textarea);
}

// 跳转查询页
const goTo = async (id, type) => {
  router.push(`/check`); // 路由跳转
}
</script>

<template>
  <!-- #f7f8fa   rgb(109 171 230)-->
  <div style="background-color: #f7f8fa; padding-top: 20px; padding-bottom: 60px;">

    <!-- <van-grid :column-num="3">
      <van-grid-item
        v-for="value in contentList"
        :key="value"
        icon="photo-o"
        :text="value"
      />
    </van-grid> -->
    <van-form ref="formRef" @submit="onSubmit" colon label-width='64'>
      <van-cell-group inset style="border: 1px solid #ddd;">
        <div class="pl-[12px] border-l-[3px] border-[color:#41b883] ml-[12px] mb-[12px]">
          <van-row>
            <van-col span="">
              <div class="font-bold text-[18px] my-[4px]">问题反馈</div>
            </van-col>
            <van-col span="">
              <van-divider vertical :style="{ borderColor: '#1989fa', }" style="margin-top: 12px;" />
              <van-button plain round icon="search" type="primary" size="mini" @click="goTo" style="
                  padding: 0 10px;
                  height: 26px;
                  margin-top: 8px;">查询我的反馈</van-button>
            </van-col>
          </van-row>
        </div>
        <!-- <br> -->
        <!-- 标题 -->
        <van-field v-model="formData.title" label="标题" placeholder="请输入标题" required
          :rules="[{ required: true, message: '请填写标题' }]" type="textarea" rows="2" autosize maxlength="50" />
        <!-- 类型 -->
        <van-field v-model="type" is-link readonly label="类型" placeholder="点击选择问题类型" required
          :rules="[{ required: true, message: '请正确填写' }]" @click="showPicker_type = true" />
        <van-popup v-model:show="showPicker_type" position="bottom">
          <van-picker :columns="columns_type" @confirm="onConfirm_type" @cancel="showPicker_type = false" />
        </van-popup>
        <!-- 区县 -->
        <van-field v-model="county" is-link readonly label="区县" placeholder="点击选择所属区县" required
          :rules="[{ required: true, message: '请正确填写' }]" @click="showPicker_county = true" />
        <van-popup v-model:show="showPicker_county" position="bottom">
          <van-picker :columns="columns_county" @confirm="onConfirm_county" @cancel="showPicker_county = false" />
        </van-popup>
        <!-- 小区 -->
        <van-field v-model="formData.community" label="小区" placeholder="请输入小区" required
          :rules="[{ required: true, message: '请正确填写' }]" />
        <!-- 姓名 -->
        <van-field v-model="formData.contacts" label="姓名" placeholder="请输入姓名" required
          :rules="[{ required: true, message: '请正确填写' }]" />
        <!-- 电话 -->
        <van-field v-model="formData.mobile" label="电话" placeholder="请输入电话" required :rules="[
          { required: true, message: '请正确填写' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
        ]" />
        <!-- 内容 -->
        <van-field v-model="formData.content" label="内容" placeholder="请输入内容" required
          :rules="[{ required: true, message: '请正确填写' }]" type="textarea" rows="6" autosize maxlength="1000" />
        <!-- 验证码 -->
        <van-field v-model="formData.captcha" center clearable label="验证码" placeholder="请输入验证码" required
          :rules="[{ required: true, message: '请正确填写' }]">
          <template #button>
            <!-- <img :src="captchaImgData" alt="" srcset="" style="width: 100px; height: 42px;"> -->
            <div class="image-container">
              <img :src="captchaImgData" alt="Example Image" class="image" @click="fetchData_captcha()" />
            </div>
          </template>
        </van-field>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-cell-group>
    </van-form>
    <van-dialog v-model:show="show" title="提交成功" show-cancel-button>
      <div>
        <div style="margin: 10px; text-align: center;">{{ msg }}</div>
      </div>
      <div style="margin-bottom: 10px;">
        <van-password-input :value="code" :mask="false" info="请先截图保存！" />
      </div>
      <template #footer>
        <van-button round type="success" block style="width: 80%; margin: 20px auto ;"
          @click="copyText()">复制并关闭弹窗</van-button>
      </template>
    </van-dialog>
  </div>
</template>
<style scoped>
::v-deep .van-password-input__security {
  margin: 0 auto;
  width: 60%;
}

::v-deep .van-field__control {
  /* background-color: #fff; */
}

::v-deep .van-cell {
  background: #fff;
  line-height: 30px;
}

::v-deep .van-field__control {
  padding-left: 5px;
  border: 1px solid #b4afaf;
  border-radius: 4px;
}


::v-deep .van-cell:after {
  border: 0px solid var(--van-cell-border-color)
}

.image-container {
  display: inline-block;
  overflow: hidden;
  width: 100px;
  /* 图片容器宽度 */
  height: 42px;
  /* 图片容器高度 */
}

.image {
  width: 100%;
  /* 图片宽度与容器一致 */
  height: 100%;
  /* 图片高度与容器一致 */
  object-fit: cover;
  /* 保持宽高比填充容器 */
  transition: transform 0.3s ease-in-out;
  /* 动画效果 */
}

.image:hover {
  /* transform: scale(1.5); */
  /* 放大 1.5 倍 */
}
</style>